#include <iostream>
#include <string>
#include <cstring>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>

using namespace std;
class Client
{
public:
    Client(const uint16_t &Sport, const string &Sip) : _Sport(Sport), _Sip(Sip) {}
    void init()
    {
        _fd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_fd == -1)
        {
            cerr << "socket : " << strerror(errno) << endl;
            exit(1);
        }
        cout << "socket success" << endl;
    }
    static void *readMessage(void *arg)
    {
        int sockfd = *(static_cast<int *>(arg));
        while (true)
        {
            char buffer[1024];
            struct sockaddr_in temp;
            socklen_t temp_len = sizeof(temp);
            size_t n = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &temp_len);
            if (n >= 0)
                buffer[n] = 0;
            cout << buffer << endl;
        }

        return nullptr;
    }
    void run()
    {
        pthread_create(&_read, nullptr, readMessage, (void *)&_fd);
        pthread_detach(_read);
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(_Sport);
        addr.sin_addr.s_addr = inet_addr(_Sip.c_str());
        socklen_t len = sizeof(addr);
        while (1)
        {
            cerr << "Please input" << endl;
            string messages;
            cin >> messages;
            sendto(_fd, messages.c_str(), messages.size(), 0, (struct sockaddr *)&addr, sizeof(addr));
        }
    }

private:
    int _fd;
    uint16_t _Sport;
    string _Sip;
    pthread_t _read;
};